import {uSelectUserDevExceptionLog} from '@/api'
import ChildrenPageUtils from '@/store/extends'
import {getStorage} from '@/utils/localstoreage'
import Taro from '@tarojs/taro'

import {observable, computed, action} from 'mobx'
import {createContext} from 'react'

class Abnormal extends ChildrenPageUtils {
  @observable currentDev: SimpleDeviceData | undefined = undefined
  @observable abnormalList: Device.AbnormalLog[] = []
  @observable startTime: string | undefined = undefined
  @observable endTime: string | undefined = undefined

  @action.bound
  setCurrentDev(dev: SimpleDeviceData) {
    this.currentDev = dev
    this.abnormalList = []
    this.resetPagination()
    this.getPageData()
  }
  @action.bound
  initPageData() {
    this.abnormalList = []
    this.startTime = undefined
    this.endTime = undefined
    this.currentDev = undefined
  }
  @action.bound
  changeDateRange(s: string, e: string) {
    this.startTime = s + ' 00:00:00'
    this.endTime = e + ' 23:59:59'
    this.abnormalList = []
    this.resetPagination()
    this.getPageData()
  }

  @action.bound
  async getPageData() {
    const userId = getStorage('userId')
    if (!userId) return
    this.closeUpdate()
    Taro.showLoading()
    console.log(this.currentDev?.devId, this.startTime, this.endTime)
    let param: any = {
      userId,
      page: this.pagination.page,
      size: this.pagination.size
    }
    if (this.currentDev?.devId) param.devId = this.currentDev.devId
    if (this.startTime) param.startDate = this.startTime
    if (this.endTime) param.endDate = this.endTime
    uSelectUserDevExceptionLog(param)
      .then(res => {
        if (this.pagination.page === 1 && !res.data.list.length) {
          Taro.showModal({
            content: '此时间段内无异常记录'
          })
        }
        this.abnormalList.push(...res.data.list)
        this.updatePagination({
          page: res.data.page,
          total: res.data.total,
          totalPage: res.data.totalPage
        })
        this.openUpdate()
        Taro.hideLoading()
      })
      .catch(err => {
        this.openUpdate()
        this.delPage()
        Taro.hideLoading()
      })
  }
}
export const AbnormalStore = createContext(new Abnormal())
